package com.suhu.admin.handlers;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.springframework.data.domain.Sort.Direction.fromString;

/**
 * Created by Administrator on 13-12-21.
 */
public class PaginationInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String page = request.getParameter("page");
        if (page != null) {
            Pageable pageable;
            String size = request.getParameter("size");
            size = size == null ? "10" : size;
            String sortby = request.getParameter("sortby");
            if (sortby == null) {
                pageable = new PageRequest(Integer.parseInt(page) - 1, Integer.parseInt(size));
            } else {
                int i = sortby.lastIndexOf("_");
                String prop = sortby.substring(0, i);
                String dest = sortby.substring(i + 1);
                pageable = new PageRequest(Integer.parseInt(page) - 1, Integer.parseInt(size), fromString(dest), prop);
            }
            request.setAttribute("pageRequest", pageable);
        }
        return true;
    }
}
